<template>
    <div id="bar" ref="chartDom" style="width: 100%; height: 100%;"></div>
</template>

<script setup>
import * as echarts from 'echarts';
import { nextTick, reactive, ref, toRefs, watch } from 'vue';

const props = defineProps({
  option: {
    type: Object,
    default: {},
  },
  Xdata: {
    type: Array,
    default: [],
  },
  seriesData: {
    type: Array,
    default: [23, 24, 18, 25],
  },
});
const chartDom = ref(null)
let myChart = reactive({})
let option = reactive({})

const getEchartsData = (_option) => {
  option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      top: '10%',
      left: '5%',
      right: '5%',
      bottom: '10%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: props.Xdata
    },
    yAxis: {
      type: 'value',
      boundaryGap: [0, 0.01]
    },
    series: [
      {
        type: 'bar',
        data: props.seriesData
      },
    ]
  };
  option && myChart.setOption(_option ? _option : option, { notMerge: true });
  myChart.resize();
}
nextTick(() => {
  myChart = echarts.init(chartDom.value);
  getEchartsData();
  window.addEventListener('resize', () => {
    myChart.resize();
  });
});

const updateEchart = () => {
  nextTick(()=>{
    const newData = {
      xAxis: {
        data: props.Xdata
      },
      series: {
        data: props.seriesData
      }
    }
    myChart.setOption(newData);
    myChart.resize();
  })
}
defineExpose({
  updateEchart
})

watch(() => props.Xdata, (newVal, oldVal) => {
  updateEchart();
}, { deep: true });
</script>